<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/16
 * Time: 16:52
 */

namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\model\Admin;
use think\facade\Config;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Session;

class Login extends Base
{
    public function initialize(){

    }

    public function index(){
        # 判断是否重复登陆
        $this->logined();
        return $this->view->fetch();
    }

    private function _doLogin(){
        $account = Request::param('account', '');
        $password = Request::param('password', '');
        if (empty($account) || empty($password)){
            $this->ckJsonReturn();
        }
        $err_msg = '用户名或者密码不正确';
        $user = Admin::where('account', $account)->find();
        if (is_null($user)){
            $this->ckJsonReturn($err_msg);
        }
        if ($user['password'] != sha1($password)){
            $this->ckJsonReturn($err_msg);
        }
        return $user;
    }

    # 处理登陆
    public function doLogin(){
        $this->checkIsAjax();
        # 处理登陆
        $user = $this->_doLogin();
        # 保存登陆状态
        Session::set('admin_info', $user);
        # 判断是否记住密码
        $remember = Request::param('remember', 0);
        if ($remember == 1){
            # 处理下一次自动登录
            $value = $user['account'] . '|' . $user['password'];
            $value = encryption($value);
            Cookie::set('auto_admin', $value, [
                'expire'    => 3600*24*7,   # cookie 保存时间
                'path'      => '/',         # cookie 保存路径
            ]);
        }
        $this->ckJsonReturn('登陆成功',1, ['go_url'=>'/admin.php']);
    }

    # 退出登陆
    public function logout(){
        Session::clear();
        $this->redirect('login/index');
    }
}